package com.zhuoxin.dao.system;

import java.io.Serializable;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Restrictions;

import com.zhuoxin.bean.system.Category;
import com.zhuoxin.bean.system.CategorySO;
import com.zhuoxin.dao.BaseDAOImpl;

public class CategoryDAOImpl extends BaseDAOImpl<Category, CategorySO> implements CategoryDAO {

	@Override
	public String getHqlWhere(CategorySO so) {
		return null;
	}

	@Override
	public void setCriteriaParams(Criteria criteria, CategorySO so) {
		if(so.getCategory()!=null){
			criteria.createAlias("category", "c");
			if(so.getCategory().getId()!=null){
				criteria.add(Restrictions.eq("c.id", so.getCategory().getId()));
			}
			
			if(StringUtils.isNotEmpty(so.getCategory().getName())){
				criteria.add(Restrictions.ilike("c.name", "%"+StringUtils.trim(so.getCategory().getName())+"%"));
			}
			
			if(StringUtils.isNotEmpty(so.getCategory().getCode())){
				criteria.add(Restrictions.eq("c.code", StringUtils.trim(so.getCategory().getCode())));
			}
		}
		
		if(StringUtils.isNotEmpty(so.getName())){
			criteria.add(Restrictions.ilike("name", "%"+StringUtils.trim(so.getName())+"%"));
		}
		
		if(StringUtils.isNotEmpty(so.getCode())){
			criteria.add(Restrictions.eq("code", StringUtils.trim(so.getCode())));
		}
		
		if(so.getSort()!=null){
			criteria.add(Restrictions.eq("sort", so.getSort()));
		}
	}

	@Override
	public void setQueryParams(Query query, CategorySO so) {
		
	}

	@Override
	public void switchVO2PO(Category po, CategorySO so) {
		if(StringUtils.isNotEmpty(so.getName())){
			po.setName(StringUtils.trim(so.getName()));
		}
		
		if(StringUtils.isNotEmpty(so.getCode())){
			po.setCode(StringUtils.trim(so.getCode()));
		}
		
		if(so.getSort()!=null){
			po.setSort(so.getSort());
		}
		
		if(so.getCategory()!=null && so.getCategory().getId()!=null){
			Category category=findById(Category.class, so.getCategory().getId());
			po.setCategory(category);
		}
	}

	public <T> void deleteById(Serializable id){
		Session session=getSessionFactory().getCurrentSession();
		Transaction transaction=session.beginTransaction();
		String hql="delete from Category where category.id=:categoryId";
		Query query=session.createQuery(hql);
		query.setParameter("categoryId", id);
		query.executeUpdate();
		
		hql="delete from Category where id=:id";
		query=session.createQuery(hql);
		query.setParameter("id", id);
		query.executeUpdate();
		
		transaction.commit();
	}

}
